package com.ruoyi.framework.manager.factory;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.project.monitor.domain.SysLogininfor;
import com.ruoyi.project.monitor.domain.SysOperLog;
import com.ruoyi.project.monitor.service.ISysLogininforService;
import com.ruoyi.project.monitor.service.ISysOperLogService;
import com.ruoyi.project.system.domain.SiyuBaseinfo;
import com.ruoyi.project.system.domain.SiyuCharge;
import com.ruoyi.project.system.domain.SiyuQuery;
import com.ruoyi.project.system.mapper.SiyuBaseinfoMapper;
import com.ruoyi.project.system.mapper.SiyuChargeMapper;
import com.ruoyi.project.system.mapper.SiyuQueryMapper;
import com.ruoyi.project.system.service.ISiyuQueryService;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author ruoyi
 */
public class AsyncFactory {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");


    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr();
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
            }
        };
    }

    /*** 校验三要素
     *
     * @param queryId
     * @param baseInfoId
     * @return
     */
    public static TimerTask disThreeElementAuth(final Long queryId, final Long baseInfoId) {
        return new TimerTask() {
            @Override
            public void run() {
                SiyuQuery siyuQuery = SpringUtils.getBean(ISiyuQueryService.class).selectSiyuQueryByQueryId(queryId.intValue());

                String baseReqSn = "RYC" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase();
                JSONObject params = new JSONObject();
                params.put("req_time", System.currentTimeMillis());
                // 手机三要素
                params.put("request_sn", baseReqSn + "JF007");
                params.put("inter_id", "JF007");
                params.put("name", siyuQuery.getName());
                params.put("cardNo", siyuQuery.getCardNo());
                params.put("mobile", siyuQuery.getTel());
                String sjsys = HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params.toJSONString(), true, "application/json");
                SpringUtils.getBean(SiyuBaseinfoMapper.class).updateSiyuBaseinfo(new SiyuBaseinfo(baseInfoId, sjsys));
            }
        };
    }

    /*** 扣费
     *
     * @param
     * @return
     */
    public static TimerTask fee(final SiyuQuery siyuQuery, final String pro) {
        return new TimerTask() {
            @Override
            public void run() {
                SpringUtils.getBean(ISiyuQueryService.class).fee(siyuQuery, pro);
            }
        };
    }

}
